package common.kubernetes.constant;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.constant.dic.intf.IEnumCombobox;

/***
 * k8s的资源类型
 * 
 * @author andy.zhou
 * 
 */
public enum ResourcesType implements IEnumCombobox {
	Service("网络", "Service", new String[] { "NAME", "TYPE", "CLUSTER-IP", "EXTERNAL-IP", "PORT(S)", "AGE" }),

	Deployment("部署", "Deployment", new String[] { "NAME", "DESIRED", "CURRENT", "UP-TO-DATE", "AVAILABLE", "AGE" }),

	Pod("Pod", "Pod", new String[] { "NAME", "READY", "STATUS", "RESTARTS", "AGE" }),

	Unknown("不支持的类型", "Unknown", new String[] {});

	private final String desc;
	private final String desc_en;
	private final String[] colNames;

	private ResourcesType(String desc, String desc_en, String[] colNames) {
		this.desc = desc;
		this.desc_en = desc_en;
		this.colNames = colNames;
	}

	public String getDesc() {
		return desc;
	}

	public String getName() {
		return this.name();
	}

	public String[] getColNames() {
		return colNames;
	}

	@Override
	public String getDesc_zh() {
		return this.desc;
	}

	@Override
	public String getDesc_en() {
		return this.desc_en;
	}

	/***
	 * 需要从k8s里取出来的值 ,eg: helm status binlog-test-db-user-info 没取出来就是出问题了
	 * 
	 * @param valueStr
	 * @return
	 */
	public String getColValue(String valueStr, String colName) {
		int indexOf = ArrayUtils.indexOf(this.colNames, colName);
		if (StringUtil.isNull(valueStr) || indexOf < 0) {
			return "";
		}
		String[] mens = valueStr.replaceAll("\\s+", "|").split("\\|");
		return mens[indexOf];
	}

	// 需要从k8s里取出来的值 ,eg: helm status binlog-test-db-user-info 没取出来就是出问题了
	public static Map<ResourcesType, String> readResources(String resourcesStr) {
		String[] split = resourcesStr.split("\n");
		ResourcesType curType = Unknown;
		Map<ResourcesType, String> retmap = new HashMap<>();
		int no = 0;
		for (String ele : split) {
			if (StringUtil.isNull(ele)) {
				continue;
			}
			if (curType == Unknown) {
				for (ResourcesType rst : ResourcesType.values()) {
					if (ele.contains("/" + rst.name())) {
						curType = rst;
						break;
					}
				}
				continue;
			}
			if (curType == Unknown) {
				continue;
			} else {
				if (no == 1) {
					retmap.put(curType, ele);
					no = 0;
					curType = Unknown;
				} else {
					if(ele.startsWith("NAME ")) {
						no++;
					}else if(StringUtil.isNotNull(ele)) {
						retmap.put(curType, ele);
						no = 0;
						curType = Unknown;
					}
				}
			}
		}
		return retmap;
	}

	public static ResourcesType find(String name) {
		if (StringUtils.isEmpty(name)) {
			return null;
		}
		for (ResourcesType ele : ResourcesType.values()) {
			if (name.equalsIgnoreCase(ele.name())) {
				return ele;
			}
		}
		return Unknown;
	}
}
